<template>
  <div>
    <div>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="日期" prop="time">
          <el-date-picker
            v-model="form.time"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <el-select style="width: 100%" v-model="form.userId">
            <el-option v-for="item in allUsers" :key="item.id" :value="item.id" :label="item.username"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="低压" prop="pressurelow">
          <el-input v-model="form.pressurelow" placeholder="血压"></el-input>
        </el-form-item>
        <el-form-item label="高压" prop="pressurehigh">
          <el-input v-model="form.pressurehigh" placeholder="高压"></el-input>
        </el-form-item>
        <el-form-item label="血糖" prop="sugar">
          <el-input v-model="form.sugar" placeholder="血糖"></el-input>
        </el-form-item>
        <el-form-item label="体重(公斤)" prop="weight">
          <el-input v-model="form.weight" placeholder="体重"></el-input>
        </el-form-item>
      </el-form>
      <div style="display: flex;margin-bottom: 20px;">
        <el-button style="margin: auto;" type="primary" @click="addUserData">录入</el-button>
      </div>
    </div>
    <div class="search">
      <el-input placeholder="请输入账号查询" style="width: 200px" v-model="username"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" strip>
        <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="头像">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 40px; height: 40px; border-radius: 50%" v-if="scope.row.avatar"
                        :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="showData(scope.row)">查看数据</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="身体数据" :visible.sync="fromVisible" width="80%" :close-on-click-modal="false" destroy-on-close>
      <div class="chart">
        <div id="line" style="height: 400px"></div>
      </div>
      <div class="analysis" v-if="analysisData.length">
        {{ analysisData.join(';') }}。
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fromVisible = false;">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
const lineOption = {
  title: {
    text: '身体数据统计与分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    left: 'left'
  },
  xAxis: {
    type: 'category',
    data: [],
  },
  yAxis: {
    type: 'value'
  },
  series: []
}
import * as echarts from 'echarts'
export default {
  name: "Data",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      username: null,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        userId: [{required: true, message: '请选择', trigger: 'blur'}],
        time: [{required: true, message: '请选择', trigger: 'blur'}],
        pressurelow: [{required: true, message: '请输入', trigger: 'blur'}],
        pressurehigh: [{required: true, message: '请输入', trigger: 'blur'}],
        sugar: [{required: true, message: '请输入', trigger: 'blur'}],
        weight: [{required: true, message: '请输入', trigger: 'blur'}],
      },
      ids: [],
      allUsers: [],
      allUserDatas: [],
      chartData: [],
      analysisData: [],
    }
  },
  created() {
    this.load(1)
    this.getAllUser()
    this.getAllUserData();
  },
  methods: {
    getAllUserData() {
      this.$request({
        url: '/bodydata/selectAll',
        method: 'GET',
      }).then(res => {
        this.allUserDatas = res.data
      })
    },
    getAllUser() {
      this.$request({
        url: '/user/selectAll',
        method: 'GET',
      }).then(res => {
        this.allUsers = res.data
      })
    },
    showData(row) {
      this.analysisData = []
      this.chartData = []
      this.fromVisible = true
      this.$nextTick(() => {
        this.chartData = this.allUserDatas.filter(v => v.userId === row.id)
        let chartData = JSON.parse(JSON.stringify(this.chartData))
        chartData = chartData.sort((a, b) => {
          return moment(a.time).valueOf() - moment(b.time).valueOf()
        })
        let lineDom = document.getElementById('line');
        let lineChart = echarts.init(lineDom);
        lineOption.xAxis.data = chartData.map(v => v.time)
        lineOption.series = [
          {
            data: chartData.map(v => v.pressurelow),
            type: 'line',
            name: '低压'
          },
          {
            data: chartData.map(v => v.pressurehigh),
            type: 'line',
            name: '高压'
          },
          {
            data: chartData.map(v => v.sugar),
            type: 'line',
            name: '血糖'
          },
          {
            data: chartData.map(v => v.weight),
            type: 'line',
            name: '体重'
          }
        ]
        lineChart.setOption(lineOption)
        // 分析体重
        const totalChange = chartData[chartData.length - 1].weight - chartData[0].weight;
        const averageDailyChange = totalChange / (chartData.length - 1);
        if (totalChange > 0 && averageDailyChange > 0) {
          this.analysisData.push('当前用户体重持续增加，请注意观察')
        } else if (totalChange < 0 && averageDailyChange < 0) {
          this.analysisData.push('当前用户体重持续降低，请注意营养补充')
        }
        // 分析血糖
        let lastSevenData = chartData.slice(-7)
        if (lastSevenData.some(v => v.sugar > 7.8)) {
          this.analysisData.push('当前用户血糖异常，请注意观察')
        }
        // 分析血压
        if (lastSevenData.some(v => v.pressurelow < 60 || v.pressurelow > 80)) {
          this.analysisData.push('当前用户低压异常，请注意观察')
        }
        if (lastSevenData.some(v => v.pressurehigh > 120)) {
          this.analysisData.push('当前用户高压异常，请注意观察')
        }
      })
    },
    addUserData() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let row = this.allUserDatas.find(v => v.userId === this.form.userId && moment(this.form.time).format('YYYY-MM-DD') == moment(v.time).format('YYYY-MM-DD'))
          if (row) {
            // 编辑
            this.$request({
              url: '/bodydata/update',
              method: 'PUT',
              data: {
                ...this.form,
                time: moment(this.form.time).format('YYYY-MM-DD'),
                id: row.id
              }
            }).then(res => {
              if (res.code === '200') {
                this.$message.success('信息录入成功')
                this.getAllUserData();
              } else {
                this.$message.error(res.msg)
              }
            })
            return
          }
          this.$request({
            url: '/bodydata/add',
            method: 'POST',
            data: {
              ...this.form,
              time: moment(this.form.time).format('YYYY-MM-DD')
            }
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('信息录入成功')
                this.getAllUserData();
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/user/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/user/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/user/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
      })
    },
    reset() {
      this.username = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.avatar = response.data
    },
  }
}
</script>

<style scoped>

</style>